package com.ai.task;

import cn.hutool.core.util.StrUtil;
import com.ai.constant.SystemConst;
import com.ai.dao.mapper.BfmUserMapper;
import com.ai.utils.Base64Util;
import com.ai.utils.DesECBUtil;
import com.ai.utils.FTPUtil;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Description
 * @ClassName 用户角色权限同步
 * @Author User
 * @date 2023.06.25
 */

@Component
@EnableScheduling
public class SyncRoleAndPermissions implements SchedulingConfigurer {

    @Autowired
    BfmUserMapper bfmUserMapper;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(() -> process(),
                triggerContext -> {
                    String cron = bfmUserMapper.getCron(2);
                    if (cron.isEmpty()) {
                        System.out.println("cron is null");
                    }
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                });
    }

    private void process() {
        //测试环境
        String ftp_ip = "136.25.32.211";
        Integer ftp_port = 30003;
        String ftp_username = "KITt";
        String ftp_password = "EY@ozei3041";
        String ftp_path = "/dfs://ftpapp/KITt/datafile/cqdxai/";
        //生产环境-IP
//        String ftp_ip = "136.25.32.211";
        //生产环境-域名
//        String ftp_ip = "ryzsjftp.cq.ctc.com";
//        Integer ftp_port = 30006;
//        String ftp_username = "edasftp";
//        String ftp_password = "UN@hbxi1064";
//        String ftp_path = "/dfs://ftpapp/data/datafile/edasftp/cqdxai/";
        System.out.println("开始生成目标系统帐号拥有的角色/权限关系文件=============================>>>>>>>>>>>>>");
        //获取前一天时间
        String date = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDateTime.now().minusDays(1));
        FTPUtil ftpUtil = null;

        //生成文件一：目标系统帐号拥有的角色/权限关系
        StringBuffer sb1 = new StringBuffer();
        List<Map<String, Object>> userAndRolesRel = bfmUserMapper.queryUserAndRolesRel();
        for (Map<String, Object> map : userAndRolesRel) {
            String sysUserCode = MapUtils.getString(map, "USER_CODE");
            //账号问题特殊处理
            if ("huangbo".equals(sysUserCode)) {
                sysUserCode = "huangbo6";
            }
            if ("Mokundong".equals(sysUserCode)) {
                sysUserCode = "mokundong";
            }
            String sysRoleId = MapUtils.getString(map, "ROLE_ID");
            String sysRoleName = MapUtils.getString(map, "ROLE_NAME");
            sb1.append(sysUserCode + "|$|" + sysRoleId + "|$|" + sysRoleName + "|$|" + "1100" + "|$|" + "CQDXAI" + "|$||$||$||$||$|" + "\n");
        }
        String userAndRolesRelData = sb1.toString();
        String fileName2 = "staff_role_info_" + date + ".dat";
        ftpUtil = new FTPUtil(ftp_ip, ftp_port, ftp_username, ftp_password, ftp_path);
        ftpUtil.uploadFile(new ByteArrayInputStream(userAndRolesRelData.getBytes()), ftp_path, fileName2);
        System.out.println("目标系统帐号拥有的角色/权限关系文件生成成功=============================>>>>>>>>>>>>>");

        //生成文件二：目标系统角色与权限关系
        System.out.println("开始生成目标系统角色与权限关系文件=============================>>>>>>>>>>>>>");
        StringBuffer sb2 = new StringBuffer();
        List<Map<String, Object>> systemRoles = bfmUserMapper.querySystemRoles();
        for (Map<String, Object> systemRole : systemRoles) {
            //目标系统角色与权限关系
            String sysRoleId = MapUtils.getString(systemRole, "role_id");
            String sysRoleName = MapUtils.getString(systemRole, "role_name");
            String privName = MapUtils.getString(systemRole, "priv_name");
            String privId = MapUtils.getString(systemRole, "priv_id");
            sb2.append("CQDXAI" + "|$|" + sysRoleName + "|$|" + sysRoleId + "|$|" + privName + "|$|" + privId + "\n");
        }
        String systemRolesData = sb2.toString();
        //文件名
        String fileName = "role_permission_info_" + date + ".dat";
        ftpUtil = new FTPUtil(ftp_ip, ftp_port, ftp_username, ftp_password, ftp_path);
        ftpUtil.uploadFile(new ByteArrayInputStream(systemRolesData.getBytes()), ftp_path, fileName);
        System.out.println("目标系统角色与权限关系文件生成成功=============================>>>>>>>>>>>>>");

        System.out.println("开始生成目标系统帐号与统一认证帐号关系文件=============================>>>>>>>>>>>>>");
        String userState = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowDate = sdf.format(new Date());
        //生成文件三：目标系统帐号与统一认证帐号关系
        StringBuffer sb3 = new StringBuffer();
        List<Map<String, Object>> systemUser = bfmUserMapper.querySystemUser();
        for (Map<String, Object> map : systemUser) {
            String sysUserId = MapUtils.getString(map, "user_id");
            String sysUserCode = MapUtils.getString(map, "user_code");
            //账号问题特殊处理
            if ("huangbo".equals(sysUserCode)) {
                sysUserCode = "huangbo6";
            }
            if ("Mokundong".equals(sysUserCode)) {
                sysUserCode = "mokundong";
            }
            String userName = MapUtils.getString(map, "user_name");
            String phone = MapUtils.getString(map, "phone");
            String state = MapUtils.getString(map, "state");
            if (StrUtil.isNotBlank(phone)) {
                try {
                    phone = Base64Util.encode(DesECBUtil.encrypt(phone, SystemConst.PHONE_KEY));
                    if ("liunian".equals(sysUserCode)) {
                        phone = "18184002419";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else {
                phone = "17353262750";
            }

            if ("A".equals(state)) {
                userState = "00";
            } else {
                userState = "01";
            }

            List<Map<String, Object>> roles = bfmUserMapper.queryRolesById(sysUserId);
            List<String> list = new ArrayList<>();
            for (Map<String, Object> role : roles) {
                String sysRoleId = MapUtils.getString(role, "role_id");
                list.add(sysRoleId);
            }
            if (list.isEmpty()) {
                continue;
            }
            if (list.contains("747")) {
                sb3.append(sysUserCode + "|$|" + "CQDXAI" + "|$|" + sysUserCode + "|$|" + userName + "|$|" + "2001" + "|$|" + userState + "|$||$|"
                        + phone + "|$|" + "1299004842" + "|$|" + "大数据和AI中心" + "|$|" + "1298089793" + "|$|" + "AI应用部" + "|$|" + nowDate + "|$||$||$|" + "\n");
                continue;
            } else {
                sb3.append(sysUserCode + "|$|" + "CQDXAI" + "|$|" + sysUserCode + "|$|" + userName + "|$|" + "1001" + "|$|" + userState + "|$||$|"
                        + phone + "|$|" + "1299004842" + "|$|" + "大数据和AI中心" + "|$|" + "1298089793" + "|$|" + "AI应用部" + "|$|" + nowDate + "|$||$||$|" + "\n");
                continue;
            }
        }
        String systemUserData = sb3.toString();
        String fileName3 = "person_staff_info_" + date + ".dat";
        ftpUtil.uploadFile(new ByteArrayInputStream(systemUserData.getBytes()), ftp_path, fileName3);
        System.out.println("目标系统帐号与统一认证帐号关系文件生成成功=============================>>>>>>>>>>>>>");
    }
}
